import { Controller, Get, Post, Query, Req } from '@nestjs/common';
import { $Api } from '../utils/index';
import { CommandRecord } from '../models/command_record';

@Controller('/api/command')
export class CommandController {
  @Get('/')
  async gets(@Req() request: any, @Query() query: any) {
    const { account_id } = request.user;
    const { offset = 0, limit = 10 } = query;
    const result = await CommandRecord.findAndCountAll({
      where: { account_id },
      offset: +offset,
      limit: +limit,
      order: [['createdAt', 'DESC']]
    });
    return Promise.resolve(result);
  }
  @Post('/')
  async command(@Req() request: any) {
    const { account_id } = request.user;
    const { code, value } = request.body;
    const row: any = { account_id, code, value, succeed: false };
    try {
      const res = await $Api.post('/api/phoneCall');
      console.log(res);
      row.succeed = true;
      await CommandRecord.create(row);
      return Promise.resolve();
    } catch (error) {
      row.succeed = false;
      await CommandRecord.create(row);
      return Promise.reject(error);
    }
  }
}
